import type { Ref } from 'vue'

import type { DomainGroupModel } from '@/apis/model/domain'
import type { UserModel } from '@/apis/model/user'
import ToastUtils from '@/utils/toast'

export default function useGroupAction<T extends PromiseFn>({
  refreshFn,
  user,
  pagination,
  tableData,
  selectedRows
}: {
  refreshFn: T
  user?: UserModel
  pagination: Pagination
  tableData: Ref<any[]>
  selectedRows: Ref<any[]>
}) {
  const { setMessageBox } = useMessageBox()

  /**
   * 删除分组
   * @param group 分组信息
   */
  const handleDelete = (group: DomainGroupModel) => {
    setMessageBox({
      content: '删除后不可恢复，是否确定删除',
      title: '确定删除？',
      async submit() {
        try {
          const fn = user?.id ? deleteUserDomainGroupApi : deleteDomainGroupApi
          await fn({ id: group.id! })
          decPageByData(pagination, tableData)
          refreshFn()
          ToastUtils.success('删除成功')

          setMessageBox({ visible: false })
        } finally {
          setMessageBox({ loading: false })
        }
      }
    })
  }

  const handleEditRemark = async (row: DomainGroupModel, remark: string) => {
    const fn = user?.id ? putUserDomainGroupApi : putDomainGroupApi
    await fn({ id: row.id!, remark })
    refreshFn()
    ToastUtils.success('修改成功')
  }

  /**
   * 批量删除分组
   */
  const handleBatchDelete = (rows: DomainGroupModel[]) => {
    const ids = rows.map(item => item.id) as string[]

    setMessageBox({
      content: '删除后不可恢复，是否确定删除',
      title: '确定删除？',
      async submit() {
        try {
          const fn = user?.id
            ? deleteUserDomainGroupsApi
            : deleteDomainGroupsApi
          await fn({ ids })
          decPageByData(
            pagination,
            tableData,
            selectedRows.value ? selectedRows : ref([])
          )
          refreshFn()
          ToastUtils.success('删除成功')

          setMessageBox({ visible: false })
        } finally {
          setMessageBox({ loading: false })
        }
      }
    })
  }

  return {
    handleEditRemark,
    handleDelete,
    handleBatchDelete
  }
}
